package PIPL::File::LockTest;

use strict;

use base 'Test::Unit::TestCase';

use PIPL::File::Lock;

use PIPL::System::Path;

use Exception::Base;
use File::Spec;
use File::Temp;

my ($tmpdir, $file);

sub set_up {
    $tmpdir = File::Temp::tempdir or die "Cannot tempdir";
    $file = File::Spec->catfile($tmpdir, 'file');
}

sub tear_down {
    File::Path::rmtree($tmpdir) if $tmpdir;
}

sub new {
    my $self = shift()->SUPER::new(@_);
    return $self;
}

sub test_PIPL_System_Path___isa {
    my $self = shift;
    my $obj = PIPL::File::Lock->new;
    $self->assert_not_null($obj);
    $self->assert($obj->isa('PIPL::File::Lock'));
}

sub test_PIPL_System_Path_lock {
    my $self = shift;

    # Create lock object
    my $obj1 = PIPL::File::Lock->new(file=>$file);
    $self->assert_not_null($obj1);
    $self->assert($obj1->isa('PIPL::File::Lock'));

    # Lock
    $self->assert_equals(1, $obj1->lock);

    # Already locked
    $self->assert_null($obj1->lock);

    # Check the file
    $self->assert_not_null($obj1->{lock_file});
    $self->assert_not_null(-f $obj1->{lock_file});

    # Another lock for same file
    my $obj2 = PIPL::File::Lock->new(file=>$file, max_tries=>1);
    $self->assert_not_null($obj2);
    $self->assert($obj2->isa('PIPL::File::Lock'));
    try Exception::Base eval {
        $obj2->lock;
    };
    my $e2 = catch Exception::Base;
    $self->assert($e2->isa('Exception::Lock'));

    # Unlock
    $self->assert_equals(1, $obj1->unlock);

    # Already unlocked
    $self->assert_null($obj1->unlock);

    # Check the file
    $self->assert_not_null($obj1->{lock_file});
    $self->assert_null(-f $obj1->{lock_file});
}

1;
